# -*- coding: utf-8 -*-
import urllib2
from Queue import Queue
import time
import logging
import json

que_end = Queue(maxsize=0)


def json_post(url, cmd):
    try:
        value = json.dumps(cmd)
        req = urllib2.Request(url, value, {'Content-Type': 'application/json'})

        ret = urllib2.urlopen(req, timeout=1000)
        ret = ret.read()
        ret = json.loads(ret)
        return ret
    except urllib2.HTTPError as e:
        print(e)
        return None


def host():
    host = "http://127.0.0.1"
    return host


def host_db(url):
    h = host()

    if h == "http://127.0.0.1":
        return "%s:9981/cfgdb/%s" % (h, url)

    return "%s/cfgdb/%s" % (h, url)


def get_log(name):
    fh = logging.handlers.RotatingFileHandler("./log/%s.log" % name, mode='a', maxBytes=1024 * 1024 * 10, encoding='utf-8')
    format = logging.Formatter("%(asctime)s,%(message)s")
    fh.setFormatter(format)

    log = logging.getLogger(name)

    log.addHandler(fh)
    log.setLevel(logging.INFO)

    return log


def tm_diff(s, e):
    diff = int((e - s) * 1000)
    return diff


def plog(name, s, c, wsn):
    e = time.time()
    tm = tm_diff(s, e)

    info = "%s,%s,%s,%s" % (name, c, tm, wsn)
    que_end.put(info)
